<?php

/***************************************************************************
 * name:文件管理类
 * author:Jeff.Liu
 * E-mail:ljf1279@yeah.net
 * copyRight:Jeff.Liu
 * 环境：php5.2 + --with-zip
 * 转载请保留该信息
****************************************************************************/
class fm
{
    var $dir;
    var $cdn_dir;
	var $web_domain;
    
    function fm($dir = './',$allowType = 'jpg,jpeg,png,gif,txt,doc,zip,rar,js,css,swf,as', $allowMime = '', $web_name= '', $web_domain='' ) 
    {
    	
    
        $this->dir = $dir;
        $this->allowType = $allowType;
        $this->allowMime = $allowMime;
		$this->web_domain = $web_domain;
        $this->cdn_dir = CDN_URL.$web_name.'/'.date(Y).'/'.date(m).'/'.date(d);
  
    }
    
    function __construct($dir = './', $allowType = 'jpg,jpeg,png,gif,txt,doc,zip,rar,js.css,swf,as', $allowMime = '' , $web_name = '', $web_domain='') {
    	
        $this->fm($dir, $allowType, $allowMime, $web_name, $web_domain);
    }
    
    //返回当前目录下所有文件列表
    function getFiles($dir = '') {
    	
        $arrReturn = array();
        if(empty($dir)) {
            $dir = $this->dir;
        }
        //处理文件夹信息
        if ($handle = opendir($dir)) {
        	
            while (false !== ($file = readdir($handle))) {
            	
                if ($file != "." && $file != "..") {
                	
                    if (is_dir($dir.'/'.$file)) {
                        $arrReturn['dirs'][] = $file;
                    } else {
                        $arrReturn['files'][] = $file;
                    }
                }
            }
            closedir($handle);
        }
        return $arrReturn;
    }
    
    //上传文件
    function Upload($src, $dir = '', $dest = '', $maxSize = 1024000, $allowType = '', $allowMime = '') {
    	
        if (empty($src)){
            return false;
        }
        
        $src = $_FILES[$src];
        
        if ($src['size'] > $maxSize) {
            return false;
        }
        
        if (empty($dir) || $dir == '') {
            $dir = $this->dir;
        }
        
        if (empty($allowType) || $allowType == '') {
            $allowType = $this->allowType;
        }
        
        if(empty($allowMime) || $allowMime == '') {
            $allowMime = $this->allowMime;
        }
        
        $arrMime = split(',', $allowMime);
        $arrType = split(',', $allowType);
        $arrFileExt = split('\.', $src['name']);
        $fileExt = $arrFileExt[count($arrFileExt)-1];
        
        if( !in_array($fileExt, $arrType) && !in_array($src['type'], $arrMime) )  {
            
            return false;
        }
        
        if (!is_dir($dir)) {
            $this->MakeDir($dir);
        }
        
        if (empty($dest))  {
            $dest = basename($src['name']);
        }
   

        $fdest = $dir . '/' . $dest;
    
        if (!move_uploaded_file($src['tmp_name'],$fdest)) {
            return false;
        }
        
        $str_dir = substr_count($dir, '.') > 0 ? substr($dir, 1, strlen($dir)) : $dir;
        if (substr_count($dest, '.zip') == 0) {
            $str_dir = str_replace('//', '/', $str_dir.'/'.$dest);
            $web_url = $str_dir[0] == '/' ? $this->web_domain.$str_dir : $this->web_domain.'/'.$str_dir;
            cdnInsertFile($this->cdn_dir, $web_url);
        }
        return array('file'=>$dest, 'path'=>$dir);
    }
    
    //解压缩文件
    function UnZip($src, $dir = '') {
    	
        $fdir = getcwd();
        
        if (empty($src) || !eregi("\.zip$", $src)) {
            return false;
        }
        
        if (empty($dir)) {
        	
            if ( false !== strpos($src,'/')) {
                $dir = dirname($src);
            } else {
                $dir = $this->dir;
            }
        }
        
        chdir($dir);
        $exdir = basename($src, '.zip').'/';
        $zip = zip_open($src);
        
        if ($zip) {
        	
           // @mkdir($exdir);
       
            while ($zip_entry = zip_read($zip)) {
            	
                if (zip_entry_open($zip, $zip_entry, "r")) {
                	
                    if (substr(zip_entry_name($zip_entry),-1) == '/') {
                        if (!is_dir(zip_entry_name($zip_entry))) {
                                $this->MakeDir(zip_entry_name($zip_entry), './');
                        }
                    } else {
                    	
                        if(zip_entry_filesize($zip_entry) <= 0) {
                            continue;
                        }
                        
                        $buf = zip_entry_read($zip_entry, zip_entry_filesize($zip_entry));

                        $arrMime = split(',', $this->allowMime);
                        $arrType = split(',', $this->allowType);
                        $fileExt = substr(strstr(zip_entry_name($zip_entry),'.'),1);
                        
                        if (!in_array($fileExt, $arrType) && !in_array($src['type'], $arrMime)) {
                            continue;
                        }
                        
                        if ($fp = @fopen('./'.zip_entry_name($zip_entry),'w')) {
                        	
                            fwrite($fp, $buf);
                            fclose($fp);
                            $str_dir = substr_count($dir, '.') > 0 ? substr($dir, 1, strlen($dir)) : $dir;
                        
                            $str_dir = str_replace('//', '/', $str_dir);
                            $str_dir = str_replace('//', '/', $str_dir.'/'.zip_entry_name($zip_entry));
                            $web_url = $str_dir[0] == '/' ? $this->web_domain.$str_dir : $this->web_domain.'/'.$str_dir;
                            cdnInsertFile($this->cdn_dir, $web_url);
                        }
                    }
                    zip_entry_close($zip_entry);
                }
            }
            
            zip_close($zip);
           
        }
        chdir($fdir);
    }
    
    //创建目录
    function MakeDir($dirName, $dir = '', $mod = 0777) {
    	
        if (empty($dirName)) {
            return false;
        }
        
        if(empty($dir)) {
            $dir = $this->dir;
        }
       	$dir_path = $dir.'/'.$dirName;
 		$dir_path = str_replace('.//', './', $dir_path);
 		
        return is_dir($dir_path) or ($this->MakeDir(dirname($dirName),$dir, $mod) and @mkdir($dir_path, $mod));
    }
    
    //删除目录
	function deltree($pathdir)  
	{  
		 
		if ($this->is_empty_dir($pathdir)) {  
			rmdir($pathdir);//直接删除  
			
		} else{ //否则读这个目录，除了.和..外  
			
			$d = dir($pathdir);  
			
			while ($a = $d->read())  {  
				
				if (is_file($pathdir.'/'.$a) && ($a!='.') && ($a!='..')) {
					unlink($pathdir.'/'.$a);
				} 
				
				
				//如果是文件就直接删除  
				if(is_dir($pathdir.'/'.$a) && ($a!='.') && ($a!='..'))  
				{
					//如果是目录  
					if(!$this->is_empty_dir($pathdir.'/'.$a)) {//是否为空  
						
						//如果不是，调用自身，不过是原来的路径+他下级的目录名  
						$this->deltree($pathdir.'/'.$a);  
					}  
				
					if ($this->is_empty_dir($pathdir.'/'.$a))  { //如果是空就直接删除  
						
						rmdir($pathdir.'/'.$a); 
					}  
				}  
			} 
			if ($this->is_empty_dir($pathdir.'/'.$a))  { //如果是空就直接删除  
						
				rmdir($pathdir.'/'.$a); 
			}  
			$d->close();  
		
		}  
	}  

	function is_empty_dir($pathdir)  
	{ 
		//判断目录是否为空 
		$d = opendir($pathdir);  
		$i=0; 
		 
		while($a = readdir($d)) {  
		   $i++;  
		}  
		
		closedir($d);  
		
		if ($i > 2){
			return false;
		} else {
			return true;  
		}
	} 
     //删除目录
    function MakeDirectory($dir) {    
        return is_dir($dir) or (mkdir($dir, 0777, true) or ($this->MakeDirectory(dirname($dir)) and mkdir($dir, 0777)));
    }
    
    function rm($src, $dir = '') {
    	
        if (empty($dir)) {
            $dir = $this->dir;
        }
        return @unlink($dir . '/' . $src);
    }
	
	// 单位自动转换函数
    function getRealSize($size)
    { 
        $kb = 1024;         // Kilobyte
        $mb = 1024 * $kb;   // Megabyte
        $gb = 1024 * $mb;   // Gigabyte
        $tb = 1024 * $gb;   // Terabyte
        
        if($size < $kb)
        { 
            return $size." B";
        }
        else if($size < $mb)
        { 
            return round($size/$kb,2)." KB";
        }
        else if($size < $gb)
        { 
            return round($size/$mb,2)." MB";
        }
        else if($size < $tb)
        { 
            return round($size/$gb,2)." GB";
        }
        else
        { 
            return round($size/$tb,2)." TB";
        }
    }

}
?>
<?php
include("inc/head.php");
require('./wondershare/configs/site_config.php');
function formatNav($path, $web_type) {
	
	$path = ereg_replace("^[\.\\\/]+","",$path);
	$ps = split('[\\\/]',$path);
	$nav = "<a href='?path=./&web_type=".$web_type."'>/</a>";
	
	if (count($ps) > 0) {
		$url = '';
		foreach ($ps as $key => $p) {
			if (!empty($p)) {
				
				$url .= $p.'/';
				
				if (ereg_replace("[\.\\\/]","",$url) == ereg_replace("[\.\/\\]","",$path)) {
					$nav .= "$p";
				} else {
					$nav .= "<a href='?path=$url&web_type=".$web_type."'>$p/</a>";
				}
			}
		}
	}
	return $nav;
}

if (empty($web_upload[$_GET['web_type']]['path'])) {
	
	echo '类型找不到目录！';
	exit;
}

$basepath = DOC_ROOT.$web_upload[$_GET['web_type']]['path'];

$allowType = 'jpg,jpeg,png,gif,txt,doc,zip,rar,css,htm,html,js,bmp,swf,as,php';
$allowMime = '';
chdir($basepath);

$path = isset($_POST['path']) ? $_POST['path'] : (isset($_GET['path']) ? $_GET['path']:'');
if ($path) {
	$path = ereg_replace("^[\/\\\.]+","",$path);
}

$path = './' . $path;
$path = iconv('utf-8','gb2312',ereg_replace("[\/\\]+","/",$path));

if (!is_dir($path)) {
	
	alert("目录错误", 'location',$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING']);
}

$fm = new fm($path, $allowType, $allowMime, $web_upload[$_GET['web_type']]['web_name'], $web_upload[$_GET['web_type']]['web_domain']);
$a = explode('/', $path);

if ($_REQUEST['action'] == 'del') {
	
	if ($filenames = $_REQUEST['filenames']) {
		if (is_string($filenames)) {
			$fm->rm($filenames);
		} elseif (is_array($filenames)) {
			
			foreach($filenames as $filename) {
				$fm->rm($filename);
			}
		}
	}
	 
	//删除目录
	if ($dirnames = $_REQUEST['dirpath']) {
		
		if (is_string($dirnames)) {

			$fm->deltree($dirnames);
			
		} elseif (is_array($dirnames)) {
			
			foreach($dirnames as $dirname) {
				


				$fm->deltree($dirname);
			}
		}
	}
	alert('删除成功');
	exit;
}

if ($_REQUEST['action'] == 'mkdir') {
	
	$mdir = $_REQUEST['dir'];
	
	if (eregi("[^0-9a-z_-]",$mdir)) {
		alert("目录名含有非法字符，请重试", 'location',$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING']);

	}
	
	if ($fm->MakeDir($mdir)) {
		alert("创建目录成功", 'location',$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING']);

	}
}

if ($_REQUEST['action'] == 'upload') {
	
	if ($_FILES['user_file']['name'] != '') {

		if ($fname = $fm->Upload('user_file')) {
			
			if ($_REQUEST['unzip'] == 'true') {
				$fm->UnZip($fname['file'],$fname['path']);
				$fm->rm($fname['file']);
			}
			$message = '上传成功';
		} else {
			$message = '上传失败';
		}

		alert($message,'location',$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING']);
		exit;
	}
}
?> 

<!--DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3c.org/TR/REC-html40/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<TITLE>ljf_FM 文件管理器</TITLE>
<style type="text/css">
div, ul {border:1px solid #eee}
div {margin:5px}
</style>
</head>
<body-->

<div>
<form enctype="multipart/form-data" name="fm" method="POST">
<input type="hidden" name="action" value="upload" />
<input type="hidden" name="path" value="<?php echo iconv('gb2312','utf-8',$path); ?>" />
<input type="file" name="user_file" />
<input type="checkbox" name="unzip" value="true" />zip文件自动解压缩
<input type="submit" name="sub" value="上传" />
</form>
</div>
<div style=" margin-top:20px;">
<form name="md" method="POST" onsubmit="if(this.dir.value.match(/[^0-9a-z_-]/i)){alert('目录名含有非法字符，请仅使用字母、数字或下划线');return false}return true;">
<input type="hidden" name="action" value="mkdir" />
<input type="hidden" name="path" value="<?php echo iconv('gb2312','utf-8',$path); ?>" />
<input type="text" name="dir" />
<input type="submit" name="sub" value="创建目录" />
</form>
</div>

<div>
<?php
$fs = $fm->getFiles();
$f = $fs['files'];
$d = $fs['dirs'];
?>
<form name="li" method="POST" onsubmit="return confirm('是否删除所选文件和目录？');">
<input type="hidden" name="action" value="del" />
<input type="hidden" name="path" value="<?php echo iconv('gb2312','utf-8',$path); ?>" />
<ul>
<li>
<?php echo formatNav(iconv('gb2312','utf-8',$path) , $_GET['web_type']); ?>
<!--a href="?path=<?php echo iconv('gb2312','utf-8',dirname($path)); ?>&web_type=<?php echo $_GET['web_type'];?>" title="返回上级">
<?php echo iconv('gb2312','utf-8',ereg_replace("^[\.\/\\]+","/",$path)); ?></a--></li>
<?php 
if($d):
foreach($d as $dir): 
/*判断用户是否为管理员才能有此权限或用户名为design*/

?>
<li><input type="checkbox" name="dirpath[]" value="<?php echo iconv('gb2312','utf-8',$path.'/'.$dir); ?>" /> <img src="http://cms.wondershare.com/images/file/folder.gif"  style="margin-right:10px;"/>
<a href="?path=<?php echo iconv('gb2312','utf-8',$path.'/'.$dir); ?>&web_type=<?php echo $_GET['web_type'];?>">
<?php echo iconv('gb2312','utf-8',$dir); ?></a></li>
<?php

endforeach; 
endif;
?>
</ul>

<?php 
if($f):
?>
<table width="800px; " style="margin-left:36px; border:1px solid #090;">
<tr>
<td bgcolor="#006600">文件名</td><td bgcolor="#006600" >修改时间</td><td bgcolor="#006600" >文件大小</td>
</tr>
<?php
foreach($f as $file): 

?>
<tr><td><input type="checkbox" name="filenames[]" value="<?php echo iconv('gb2312','utf-8',$file); ?>" />
<a href="<?php echo iconv('gb2312','utf-8','http://cms.wondershare.com/vhosts'.$web_upload[$_GET['web_type']]['path'].$path.'/'.$file); ?>" target="_blank">
<?php echo iconv('gb2312','utf-8',$file); ?> </a></td>

<td><?php echo date("Y-m-d H:i:s", filemtime(iconv('gb2312','utf-8',$path.'/'.$file))); ?></td>
<td><?php echo $fm->getRealSize(filesize(iconv('gb2312','utf-8',$path.'/'.$file))); ?></td>
</tr>
<?php
endforeach; 
?>
</table>
<?php
endif;
?>
<br />
<input type="submit" name="del" value="删除" style=" margin-left:40px;">
</form>
</div>
</body>
</html>